<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formItem.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请服务厅局" prop="serviceUnitCode">
            <el-select v-model="formItem.serviceUnitCode" filterable :disabled="isWorker()" placeholder="请选择申请服务厅局" @change="onChangeUnit">
              <el-option v-for="item in availableInstitutions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="事件等级" prop="eventLevel">
            <el-select v-model="formItem.eventLevel" clearable placeholder="请选择响应方式" style="width:100%">
              <el-option v-for="(item) in eventgradeList" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="一线工程师" prop="frontlineEngineerCode">
            <el-select v-model="formItem.frontlineEngineerCode" filterable clearable :disabled="isWorker()" placeholder="请选择一线工程师">
              <el-option v-for="item in availableFrontlineUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参与工程师" prop="helperEngineerCode">
            <el-select v-model="formItem.helperEngineerCode" filterable clearable placeholder="请选择参与工程师">
              <el-option v-for="item in allAvailableFrontlineUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="customerName">
            <el-input v-model="formItem.customerName" placeholder="请输入客户姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户电话" prop="customerPhone">
            <el-input v-model="formItem.customerPhone" placeholder="请输入客户电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="处室" prop="place">
            <el-input v-model="formItem.place" placeholder="请输入处室" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间号" prop="roomNumber">
            <el-input v-model="formItem.roomNumber" placeholder="请输入房间号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否备份" prop="whetherBackup">
            <el-select v-model="formItem.whetherBackup" placeholder="请选择是否备份">
              <el-option v-for="item in availableWhetheSelectOptions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否涉密" prop="whetherSecret">
            <el-select v-model="formItem.whetherSecret" placeholder="请选择是否涉密">
              <el-option v-for="item in availableWhetheSelectOptions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="故障级别" prop="failureLevel">
            <el-select v-model="formItem.failureLevel" placeholder="请选择故障级别">
              <el-option v-for="item in availableFailureLevels" :key="item.code" :label="item.text" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="变更描述" prop="eventDescription">
            <el-input v-model="formItem.eventDescription" placeholder="请输入变更描述" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              ref="upload"
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.annex"
              :before-upload="handleBeforeUpLoad"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div style="float:right">
            <el-button size="mini" type="warning" @click="ok('temporary')">保存</el-button>
            <el-button size="mini" type="primary" @click="ok('submit')">提交</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { create, detail, applyformDeleteAnnexByFsId, applyformImportUrl } from '@neu/dcom-ui/api/alter'
import { list as institutionsList } from '@neu/dcom-ui/api/institutions'
import { list as userList } from '@neu/auth-ui/api/user'
import { mapState, mapGetters } from 'vuex'
import { getToken } from '@neu/biz-core/utils/auth'
import { list as dList } from '@neu/dcom-ui/api/dictionary'

// import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'

const formItem = {
  // 标题
  title: '',
  // 工作流TaskId
  taskId: '',
  // 工单号
  workNum: '',
  // 申请服务厅局名称
  serviceUnitName: '',
  // 申请服务厅局编码
  serviceUnitCode: '',
  // 一线工程师编码
  frontlineEngineerCode: '',
  // 一线工程师名称
  frontlineEngineerName: '',
  // 参与一线工程师编码
  helperEngineerCode: '',
  // 参与一线工程师名称
  helperEngineerName: '',
  // 客户姓名
  customerName: '',
  // 客户电话
  customerPhone: '',
  // 处室
  place: '',
  // 房间号
  roomNumber: '',
  // 是否备份
  whetherBackup: true,
  // 是否涉密
  whetherSecret: false,
  // 时间等级
  eventLevel: '',
  // 事件描述
  eventDescription: '',
  // 状态
  status: 'temporary',
  // 附件
  annex: []
}

const formRules = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  serviceUnitCode: [{ required: true, message: '申请服务厅局不能为空', trigger: 'blur' }],
  frontlineEngineerCode: [{ required: true, message: '一线工程师不能为空', trigger: 'blur' }],
  failureLevel: [{ required: true, message: '故障级别不能为空', trigger: 'blur' }],
  eventDescription: [{ required: true, message: '变更描述不能为空', trigger: 'blur' }]
}

export default {
  name: 'MalfunctionApplyForm',
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      /** 上传路径 */
      importUrl: applyformImportUrl,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      // 所有的单位
      availableInstitutions: [],
      // 单位驻场一线工程师
      availableFrontlineUsers: [],
      // 所有一线工程师集合
      allAvailableFrontlineUsers: [],
      // 故障级别集合
      // availableFailureLevels: [],
      // 是否下拉框
      availableWhetheSelectOptions: [{ name: '是', code: true }, { name: '否', code: false }],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: { ...formRules },
      // 事件等级集合
      eventgradeList: []
    }
  },
  computed: {
    ...mapState({
      name: state => state.user.name
    }),
    ...mapGetters([
      'roles'
    ]),
    projectUserInfo() {
      return this.$store.getters['dcom/projectUserInfo']
    }
  },
  created() {
    this.fetch()
    userList({ 's_roleCode': 'worker' }).then(res => {
      this.allAvailableFrontlineUsers = res.data.map(e => { return { name: e.name, username: e.username } })
    })
    dList({ s_type: 'eventgrade' }).then(res => {
      this.eventgradeList = res.data
    })
  },
  mounted() {
    this.$refs.upload.clearFiles()
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }

          this.onChangeUnit(this.formItem.serviceUnitCode)
        })
      } else {
        this.formItem = {
          ...formItem
        }
        this.formItem.eventLevel = 'level4'
        this.onChangeUnit(this.projectUserInfo.defaultInstituteCode)
      }
    },
    isWorker() {
      return this.roles.some(r => r === 'worker')
    },
    isWorkerOrGroupLeader() {
      return this.roles.some(r => r === 'worker') || this.roles.some(r => r === 'workerGroupLeader')
    },
    onChangeUnit(code) {
      if (this.isWorkerOrGroupLeader()) {
        this.availableInstitutions = this.$store.getters['dcom/projectUserInfo'].institutions
        this.formItem.serviceUnitCode = code
        this.initResidentUsers(code)
      } else {
        // 所有的单位
        institutionsList().then(res => {
          this.availableInstitutions = res.data
          this.formItem.serviceUnitCode = code
          this.initResidentUsers(code)
        })
      }
    },
    initResidentUsers(code) {
      const inst = this.availableInstitutions.find(it => it.code === code)
      if (inst) {
        this.availableFrontlineUsers = inst.residents && inst.residents.map(e => { return { name: e.name, username: e.username } })
        let resident
        if (this.isWorker()) {
          resident = this.availableFrontlineUsers.find(it => it.name === this.name)
        } else {
          resident = this.availableFrontlineUsers[0]
        }
        if (resident) {
          this.formItem.frontlineEngineerCode = resident.username
          this.formItem.frontlineEngineerName = resident.name
        }
      }
    },
    ok(value) {
      this.$refs.myform.validate((valid) => {
        if (valid) {
          // 状态
          this.formItem.status = value
          // // 一线运维人员
          // const frontlineEngineer = this.availableFrontlineUsers.find(e => e.username === this.formItem.frontlineEngineerCode)
          // this.formItem.frontlineEngineerName = frontlineEngineer ? frontlineEngineer.name : ''
          // 管理厅局
          const serviceUnit = this.availableInstitutions.find(e => e.code === this.formItem.serviceUnitCode)
          this.formItem.serviceUnitName = serviceUnit ? serviceUnit.name : ''
          // 参与工程师
          const helperEngineer = this.allAvailableFrontlineUsers.find(e => e.username === this.formItem.helperEngineerCode)
          this.formItem.helperEngineerName = helperEngineer ? helperEngineer.name : ''

          create(this.formItem).then(res => {
            if (res.status === 'success') {
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          })
        }
      })
    },
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.annex.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.annex.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      applyformDeleteAnnexByFsId(file.fsId).then(res => {
        if (res.status === 'failure') {
          this.$message({
            showClose: true,
            message: res.data,
            type: 'error'
          })
        } else {
          this.formItem.annex.splice(this.formItem.annex.indexOf(file), 1)
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        }
      })
    },
    /** 文件上传之前 */
    handleBeforeUpLoad(file) {

    }
  }
}
</script>
